package com.xbongbong.rule.rules;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.api.*;
import org.jeasy.rules.core.RuleBuilder;
import com.xbongbong.rule.symbol.base.SymbolContext;

import java.util.List;


/**
 *  规则
 *  <p>
 *      用法参考 FireTest
 *  </p>
 * @author zheng.li
 * @param <T> type of Fact value
 */
@Data
@Slf4j
public class DefaultXbbRule<T> implements XbbRule<T> {

    /**
     * 规则的唯一标识(对应easy-rule的name)
     */
    protected String ruleId;

    /**
     * 优先级
     * （easyRule的规则优先级，当规则的优先级超过ruleEngine的阈值（priorityThreshold）时，则忽略此规则）
     */
    protected Integer priority = 1;

    /**
     * 规则条件设置
     */
    protected List<XbbCondition> conditionItems;

    /**
     * 规则触发逻辑类
     */
    protected XbbAction<T> xbbAction;


    @Override
    public Rule toEasyRule() {
        return new RuleBuilder().name(ruleId).priority(priority)
                .when(getEasyCondition()).build();
    }

    @Override
    public XbbAction<T> getXbbAction() {
        return xbbAction;
    }

    /**
     * 构建Condition
     * @return Condition
     */
    @SuppressWarnings("unchecked")
    private Condition getEasyCondition() {

        return new Condition() {
            @Override
            public boolean evaluate(Facts facts) {
                T factValue = (T)facts.iterator().next().getValue();
                SymbolContext symbolContext = new SymbolContext();
                for (XbbCondition item : conditionItems) {
                    symbolContext.setItem(item);
                    symbolContext.setJson(factValue);
                    if (!symbolContext.operation()) {
                        return false;
                    }
                }
                return true;
            }
        };
    }

    /**
     * 构建action
     * @return Action
     */
    @Deprecated
    private Action getEasyAction() {

        // 规则触发
        return new Action() {
            @Override
            public void execute(Facts facts) {
                  // 这里的规则触发与listener是等效的，所以这里暂时不做处理了
//                T fact = (T)facts.iterator().next().getValue();
//                log.info("规则触发!");
//                xbbAction.action(fact);
            }
        };
    }



}
